package com.xiaoshuidi.cloud.module.member.utils;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.date.LocalDateTimeUtil;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.Calendar;
import java.util.Date;

public class CardUtils {
    public static int countAge(String idCard) {
        if (idCard.length() != 18 && idCard.length() != 15) {
            throw new IllegalArgumentException("身份证号长度错误");
        }
        String year;
        String monthDay;
        if (idCard.length() == 18) {
            year = idCard.substring(6, 10);
            monthDay = idCard.substring(10, 14);
        } else {
            year = "19" + idCard.substring(6, 8);
            monthDay = idCard.substring(8, 12);
        }
        //获取当前时间字符串如：2022-1128
        String nowTimeStr = new SimpleDateFormat("yyyy-MMdd").format(new Date());
        String yearNow = nowTimeStr.substring(0, 4);// 当前年份
        String monthDayNow = nowTimeStr.substring(5, 9);// 当前月日
        int age = Integer.parseInt(yearNow) - Integer.parseInt(year);
        //age减一的情况 ：用户月日大于当前月日（开头可以为0的4位数int）
        if (Integer.parseInt(monthDay) > Integer.parseInt(monthDayNow)) {
            age = age - 1;
        }
        return age;
    }


    public static String getBirthdayFromCard(String idCard) {
        String birthday = "";
        int year = Calendar.getInstance().get(Calendar.YEAR);
        char[] number = idCard.toCharArray();
        boolean flag = true;
        if (number.length == 15) {
            for (int x = 0; x < number.length; x++) {
                flag = Character.isDigit(number[x]);
            }
        } else if (number.length == 18) {
            for (int x = 0; x < number.length - 1; x++) {
                flag = Character.isDigit(number[x]);
            }
        }
        if (flag && idCard.length() == 15) {
            birthday = "19" + idCard.substring(6, 8) + "-" + idCard.substring(8, 10) + "-" + idCard.substring(10, 12);
        } else if (flag && idCard.length() == 18) {
            birthday = idCard.substring(6, 10) + "-" + idCard.substring(10, 12) + "-" + idCard.substring(12, 14);
        }
        return birthday;
    }

}